// base
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtActivityIndicator } from 'taro-ui'
// redux
import { DOREQUESTGETSHARE } from './store/actions/pagejobdetail'
import { UPDATEPAGEJOBDETAIL } from './store/types/pagejobdetail'
import { UPDATEIM } from '../../store/types/im'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import { UPDATEPAGECHOOSEJOBINPUT } from '../../pages/choose-job-input/store/types/pagechoosejobinput'
// less
import './index.less'
import {
  getZhichuBUserInfo,
  getZhichuUserInfo,
  updateCompanyId
} from '../../store/actions/userinfo'
import JobTopDetail from './components/job-top-detail'
import JobBottomDetail from './components/job-bottom-detail'
import BtmFixedBoss from './components/btm-fixed-boss'
import { insertPostRequest, removePostRequest } from '../../service/archive-operate-controller'
import { jobDetailRequest } from '../../service/post-controller'
import { showToast } from '../../crossplatform/apiservice/toast'
import { postformatcommon } from '../../service/format/post-format'
import { openLocation } from '../../crossplatform/apiservice/location'
import scaleImageSrc from '../../util/pagemethods/scaleImageSrc'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import { postTalkRequest, getMemberTalentTalkRequest } from '../../service/member-controller'
import { getSetting } from '../../crossplatform/apiservice/setting'
import { companyInfoRequest } from '../../service/org-operator-controller'
import IMController from '../../util/wy_im'
import wxLogin from '../../util/wxLogin'
import { getUserArchiveInfoRequest } from '../../service/user-archive-controller'
import { getGlobalData } from '../../configuration/globaldata'
import { judgeLoginStatus } from '../../util/login_status'
import { hideShareMenu } from '../../crossplatform/apiservice/tabbar'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEJOBDETAIL,
      payload: {
        ...payload
      }
    })
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  getShare(payload) {
    let promise = DOREQUESTGETSHARE(payload)
    dispatch(promise)
    return promise.payload
  },
  getZhichuUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  getZhichuBUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuBUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  updateJobInput(payload) {
    dispatch({
      type: UPDATEPAGECHOOSEJOBINPUT,
      payload: {
        ...payload
      }
    })
  },
  updateCompany() {
    dispatch(updateCompanyId())
  }
})
@connect(
  ({ pagejobdetail, userinfo, landmark, im }) => ({
    ...pagejobdetail,
    landmarkName: landmark.landmarkName,
    ...userinfo,
    ...im
  }),
  mapActiontoProps
)
class JobDetail extends Component {
  config = {
    navigationBarTitleText: '岗位详情'
  }

  constructor(props) {
    super(props)
    this.state = {
      displayCover: false,
      btnLoading: false,
      hasCompanyHome: true,
      loadingData: false,
      introExit: false,
      introValue: '',
      archiveId: null,
      loadIn: false,
      dataEntry: {},
      education: [], // 当前用户的教育信息
      userArchiveWorkModels: [], // 当前用户的工作经验
      jobHuntingModels: [], // 当前用户的求职意向
      loadingPage: true
    }
  }
  componentWillMount() {
    // onLoad
    wxLogin.props = this.props
    this.setState({
      loadIn: true,
      loadingPage: true
    })
    wxLogin.doLogin().then(() => {
      IMController.queryWrap().then(() => {
        const { type, jobState } = this.$router && this.$router.params
        if (type != 'prew') {
          this.queryWrap()
        } else {
          this.setState({
            loadingPage: false
          })
          this.showMapFunc()
        }
        if (jobState && jobState !== '0') {
          hideShareMenu()
        }
      })
      this.getUserInfo()
    })
  }

  componentDidMount() {
    // onready
    this.getMyLat()
  }

  componentDidShow() {
    // onshow
    const { loadIn } = this.state
    const type = this.$router && this.$router.params && this.$router.params.type
    if (type != 'prew' && !loadIn) {
      this.queryWrap()
    } else {
      type == 'prew' &&
        this.setState({
          loadingPage: false
        })
      this.showMapFunc()
    }
    this.setState({
      btnLoading: false,
      loadingData: false
    })
    // 获取用户信息
    wxLogin.props = this.props
    wxLogin.getArchiveInfo().then(() => {
      this.getCompanyInfo()
    })
    !loadIn && this.getUserInfo()
  }

  componentDidHide() {
    // onhide
    this.setState({
      loadIn: false,
      loadingData: false
    })
  }

  componentWillUnmount() {
    // onUnload
    this.setState({
      introExit: false,
      introValue: '',
      loadIn: false,
      loadingData: false,
      loadingPage: true
    })
    this.props.updateState({
      jobtopdetail: {},
      jobbottomdetail: {},
      bossdetail: {},
      showEmpty: true
    })
  }

  queryWrap = () => {
    const { id, isOld, isCollect, share } = this.$router && this.$router.params
    const { userId, landmarkName } = this.props
    if (id && !isOld) {
      jobDetailRequest({ id: id, userId }).then(({ data }) => {
        if (data.code === 200) {
          this.props.updateState({
            ...postformatcommon(data.entry, landmarkName, isCollect || share)
          })
          this.setState({
            dataEntry: data.entry
          })
          let timer = setTimeout(() => {
            clearTimeout(timer)
            this.createWyAccount()
            this.setState({
              loadingPage: false
            })
            this.showMapFunc()
          }, 100)
        } else {
          showToast({
            title: data.message || '失败'
          })
        }
      })
    }
  }

  showMapFunc = () => {
    // let timer = setTimeout(() => {
    //   clearTimeout(timer)
    this.setState({
      displayCover: true
    })
    // }, 16)
  }

  getMyLat = () => {
    this.getLocation().then(res => {
      const { jobbottomdetail } = this.props
      const { workarea } = jobbottomdetail
      this.props.updateState({
        jobbottomdetail: {
          ...jobbottomdetail,
          workarea:
            workarea &&
            workarea.map(e => ({
              ...e
            }))
        }
      })
    })
  }
  getLocation = () => {
    return new Promise((resolve, reject) => {
      Taro.getLocation({
        type: 'gcj02',
        success: res => {
          resolve({
            latitude: res.latitude,
            longitude: res.longitude
          })
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }
  onCurrentLocationClick = () => {
    // 判断用户是否打开位置信息
    getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          Taro.showModal({
            title: '提示',
            content: '检测到您没有打开定位权限，是否去设置打开？',
            success: ress => {
              if (ress.confirm) {
                this.goSetting()
              } else if (ress.cancel) {
              }
            }
          })
        } else {
          this.getLocation().then(marker => {
            const { jobbottomdetail } = this.props || {}
            const oldLocation = jobbottomdetail.mapLocation
            let mapLocation = {
              latitude: marker.latitude,
              longitude: marker.longitude
            }
            if (
              oldLocation.latitude.toString() === marker.latitude.toString() &&
              oldLocation.longitude.toString() === marker.longitude.toString()
            ) {
              mapLocation = {
                latitude: marker.latitude - 0.00000001,
                longitude: marker.longitude
              }
            }
            this.props.updateState({
              jobbottomdetail: {
                ...jobbottomdetail,
                mapLocation
              }
            })
            this.getMyLat()
          })
        }
      }
    })
  }

  goSetting = () => {
    wx.openSetting({
      success: res => {}
    })
  }

  escAix = ({ collectionId }) => {
    console.log('执行了 1')
    removePostRequest({ ids: [collectionId] }).then(({ data }) => {
      if (data && data.entry) {
        const { jobtopdetail } = this.props || {}
        this.props.updateState({
          jobtopdetail: {
            ...jobtopdetail,
            collectionCount: jobtopdetail.collectionCount - 1,
            collectionId: null
          }
        })
      } else {
        showToast({
          title: (data && data.message) || '取消失败！'
        })
      }
    })
  }

  onInsertPost = ({ postId, userId } = {}) => {
    const { isOld } = this.$router && this.$router.params
    if (!isOld) {
      insertPostRequest({ postId, userId }).then(({ data }) => {
        if (data && data.status) {
          const { jobtopdetail } = this.props || {}
          this.props.updateState({
            jobtopdetail: {
              ...jobtopdetail,
              collectionCount: jobtopdetail.collectionCount + 1,
              collectionId: data.entry
            }
          })
        } else {
          showToast({
            title: '收藏职位失败！'
          })
        }
      })
    } else {
      showToast({
        title: '收藏职位失败！'
      })
    }
  }
  onPlaceClick = workActive => {
    const { jobbottomdetail } = this.props || {}
    const marker = jobbottomdetail.workarea[workActive]
    const oldLocation = jobbottomdetail.mapLocation
    let mapLocation = {
      latitude: marker.latitude,
      longitude: marker.longitude
    }
    if (
      oldLocation.latitude.toString() === marker.latitude.toString() &&
      oldLocation.longitude.toString() === marker.longitude.toString()
    ) {
      mapLocation = {
        latitude: marker.latitude - 0.00000001,
        longitude: marker.longitude
      }
    }

    this.props.updateState({
      jobbottomdetail: {
        ...jobbottomdetail,
        workActive,
        mapLocation
      }
    })
  }

  onOpenClick(data) {
    if (data) {
      openLocation({
        latitude: data.latitude,
        longitude: data.longitude,
        name: data.address,
        scale: 28
      })
    }
  }

  callphone = () => {
    const {
      loadingData,
      introExit,
      education,
      userArchiveWorkModels,
      jobHuntingModels
    } = this.state
    if (!loadingData) {
      const { isOld } = this.$router && this.$router.params
      const {
        role,
        userId,
        jobtopdetail: { id, companyId },
        bossdetail: { userIdB }
      } = this.props
      this.setState({
        btnLoading: true
      })
      if (role == 'company' && companyId) {
        showToast({
          title: '仅支持个人用户拨打'
        })
        this.setState({
          btnLoading: false
        })
      } else {
        if (userId) {
          if (
            (education.length || userArchiveWorkModels.length) &&
            introExit &&
            jobHuntingModels.length
          ) {
            if (!isOld) {
              // 开始沟通
              this.goChat()
              Promise.all([
                postTalkRequest({ id }),
                getMemberTalentTalkRequest({
                  companyId,
                  userId: userIdB,
                  cmpUserId: userId,
                  type: 'C',
                  postId: id
                })
              ]).then(([{ data }, { data: datain }]) => {
                const { status, message } = data
                if (status) {
                  const { message: messageIn, status: statusIn } = datain
                  if (statusIn) {
                    // 增加沟通记录
                  } else {
                    showToast({
                      title: messageIn || '沟通失败'
                    })
                  }
                } else {
                  showToast({
                    title: message || '沟通失败'
                  })
                  this.setState({
                    btnLoading: false
                  })
                }
              })
            } else {
              this.goChat()
            }
          } else {
            if (!(introExit && jobHuntingModels.length)) {
              Taro.showModal({
                title: '提示',
                content: '请完善求职意愿和自我评价后沟通',
                confirmText: '去完善',
                cancelText: '取消',
                success: ress => {
                  if (ress.confirm) {
                    this.onEditResume()
                  }
                }
              })
            } else {
              Taro.showModal({
                title: '提示',
                content: '您的教育信息不完善，无法进行沟通，快去完善简历吧',
                confirmText: '去完善',
                cancelText: '取消',
                success: ress => {
                  if (ress.confirm) {
                    this.onGoEducation()
                  }
                }
              })
            }
            this.onCancelResume()
          }
        } else {
          judgeLoginStatus({ parmas: 'detailIn=1' })
          this.onCancelResume()
        }
      }
    } else {
      console.log('数据正在加载')
    }
  }

  goChat = () => {
    let timer = setTimeout(() => {
      clearTimeout(timer)
      this.setState({
        btnLoading: false,
        loadingData: false
      })
    }, 500)
    this.props.updateImState({
      msgArray: []
    })
    navigateTo({
      url: `${pagejumplist['chat-page'].path}`
    })
  }

  createWyAccount = () => {
    // 创建网易云信账号
    this.setState({
      loadingData: true
    })
    const imId = getGlobalData('IM_ID')
    try {
      const {
        bossdetail,
        jobtopdetail: { companyName, simpleName, companyId }
      } = this.props
      let identifier = bossdetail.userIdB + 'b' + imId
      let newCompanyName = simpleName || companyName
      let userInfo = {
        userName: bossdetail.user_name,
        userAvator: bossdetail.user_avator,
        userId: bossdetail.userIdB,
        sex: bossdetail.sex,
        gmtBirth: bossdetail.birth,
        mobile: bossdetail.mobile
      }
      IMController.createAccount({
        userId: identifier,
        role: 'company',
        userInfo,
        companyName: newCompanyName,
        companyId
      }).then(() => {
        console.log(this.props.selToID, 'toididid')
        this.setState({
          loadingData: false
        })
      })
    } catch (e) {
      showToast({
        title: '创建网易云信账号失败'
      })
    }
  }

  onShareAppMessage() {
    let { params: { id } = {} } = this.$router || {}
    const userId = this.props.userId
    this.props.getShare({ id, userId }).then(data => {
      const { jobtopdetail } = this.props || {}
      this.props.updateState({
        jobtopdetail: {
          ...jobtopdetail,
          entryCount: jobtopdetail.entryCount + 1
        }
      })
    })
    return {
      title: '这有一个好职位，发给你看看～',
      path: `/pages/job-detail/index?id=${id}`,
      imageUrl: scaleImageSrc(this.props.jobtopdetail.companyLogo)
    }
    // 享次数+1
  }

  getCompanyInfo = () => {
    // 获取公司主页信息  判断是否能点击
    const { companyId } = this.$router.params
    companyInfoRequest({ companyId }).then(({ data }) => {
      const { data: datain, code } = data
      if (code === 200 && !datain.companyLogo) {
        this.setState({
          hasCompanyHome: false
        })
      }
    })
  }

  onEditResume = () => {
    // 跳转到基本信息填写页面
    const { education, userArchiveWorkModels } = this.state
    let isEducation = education.length || userArchiveWorkModels.length
    judgeLoginStatus({ parmas: `detailIn=1${isEducation ? '&educationExit=1' : ''}` })
    this.onCancelResume()
  }

  onGoEducation = () => {
    navigateTo({
      url: `${pagejumplist['education-information'].path}`
    })
  }

  onCancelResume = () => {
    // 隐藏弹框
    this.setState({
      btnLoading: false
    })
  }

  getUserInfo = () => {
    // 获取用户自我评价信息
    const { userId } = this.props
    if (userId) {
      getUserArchiveInfoRequest({ userId }).then(({ data }) => {
        const {
          entry: {
            archive: { userArchiveModel = {}, userArchiveWorkModels = [], jobHuntingModels = [] },
            education
          }
        } = data
        let { intro, id } = userArchiveModel
        if (intro && intro !== '这家伙很懒,什么都没写') {
          this.setState({
            introExit: true,
            introValue: intro,
            education,
            userArchiveWorkModels,
            jobHuntingModels,
            archiveId: id
          })
        } else {
          this.setState({
            introExit: false,
            introValue: '',
            education: [],
            userArchiveWorkModels: [],
            jobHuntingModels: [],
            archiveId: id
          })
        }
      })
    }
  }

  render() {
    const { userId, role } = this.props
    const { isOld } = this.$router && this.$router.params
    const { displayCover, btnLoading, hasCompanyHome, dataEntry, loadingPage } = this.state
    return (
      <View className={`JobDetail_id95170 ${loadingPage ? 'no-scroll' : ''}`}>
        {loadingPage && (
          <View className="loading">
            <AtActivityIndicator mode="center" />
          </View>
        )}
        <JobTopDetail
          role={role}
          detail={this.props.jobtopdetail}
          userId={userId}
          onEscAix={this.escAix}
          onInsertPost={this.onInsertPost}
          isOld={isOld}
          hasCompanyHome={hasCompanyHome}
        />
        {displayCover && (
          <JobBottomDetail
            userId={userId}
            dataEntry={dataEntry}
            jobtopdetail={this.props.jobtopdetail}
            detail={this.props.jobbottomdetail}
            onPlaceClick={this.onPlaceClick}
            onOpenClick={this.onOpenClick}
            onCurrentLocationClick={this.onCurrentLocationClick}
          />
        )}

        {displayCover && (
          <BtmFixedBoss
            displayCover
            btnLoading={btnLoading}
            detail={this.props.bossdetail}
            onTap={this.callphone}
          />
        )}
      </View>
    )
  }
}

export default JobDetail
